package com.ho1ho.springboot.framework.core.utils;

import java.util.Locale;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

public class Utils {
	public static final String LANG_JA = "ja";
	public static final String LANG_EN = "en";
	public static final String LANG_ZH = "zh";

	public static String getLangCode() {
		Locale locale = LocaleContextHolder.getLocale();
		String language = locale.getLanguage();
		if (Locale.JAPANESE.getLanguage().equals(language)) {
			return LANG_JA;
		} else {
			return LANG_EN;
		}
	}

	public static User getLoggedInUser() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken)) {
			// Returned object contains remoteAddress and sessionId
			// WebAuthenticationDetails detail = (WebAuthenticationDetails)
			// auth.getDetails();
			Object userDetails = auth.getPrincipal();
			if (userDetails instanceof UserDetails) {
				return (User) userDetails;
			}
		}
		return null;
	}

	public static String getLoggedInUserName() {
		User user = getLoggedInUser();
		return user == null ? "" : user.getUsername();
	}
}
